import { ref, reactive } from 'vue'
import app from '@/app'
import store from '@/app/store'
import { get, update, inbound } from '@/api/erp/supplier_order'

// 初始化
const supplierOrderStore = store()

// 分页
supplierOrderStore.page = reactive({
  current: 1,
  pageSize: 0,
  total: 0,
  pageSizeOptions: [10, 20, 50, 100],
  loading: false
})

// 查询类型
supplierOrderStore.where = reactive({ 
  key: 'code', 
  value: '',
  time: []
})

// 生成查询数据
supplierOrderStore.getWhere = () => {
  // 查询方式
  const where = { 
    [supplierOrderStore.where.key]: supplierOrderStore.where.value,
    time: supplierOrderStore.where.time
  }
  // 合并数据
  return Object.assign(where, supplierOrderStore.getData())
}

supplierOrderStore.get = () => {
  return new Promise((resolve, jeject) => {
    supplierOrderStore.page.loading = true
    get(supplierOrderStore.getWhere()).then(res => {
      const list = res.data.map((item, index) => {
        item.created_at = app.time.load(item.created_at)
        return item
      })
      supplierOrderStore.setList(list)
      // 分页
      supplierOrderStore.page.current = res.current_page
      supplierOrderStore.page.pageSize = res.per_page
      supplierOrderStore.page.total = res.total
      resolve(res)
    }).catch(res => {
      jeject(res)
    }).finally(() => {
      supplierOrderStore.page.loading = false
    })
  })
}

// 选中入库单
supplierOrderStore.select = ref({})
// 更新入库单
supplierOrderStore.update = () => {
  return new Promise((resolve, jeject) => {
    update(supplierOrderStore.select.value).then(res => {
      resolve(res)
    }).catch(res => {
      jeject(res)
    })
  })
}

// 重置请求
supplierOrderStore.reset = (page, size) => {
  supplierOrderStore.page.current = page
  supplierOrderStore.page.pageSize = size
  supplierOrderStore.getData().page = page
  supplierOrderStore.getData().page_size = size

  // 开始加载
  supplierOrderStore.get()
}

// 入库
supplierOrderStore.inbound = id => {
  return new Promise((resolve, jeject) => {
    inbound(id).then(res => {
      supplierOrderStore.reset(1)
      resolve(res)
    }).catch(res => {
      jeject(res)
    })
  })
}

export default supplierOrderStore